<template>
  <div class="app-container">
    <el-card>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small">
          <el-form-item label="渠道分类：">
            <el-select
              v-model="listQuery.categoryId"
              placeholder="全部"
              clearable
              class="input-width"
            >
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态：">
            <el-select
              v-model="listQuery.enableStatus"
              placeholder="全部"
              clearable
              class="input-width"
            >
              <el-option label="未启用" value="0"></el-option>
              <el-option label="启用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-refresh"
              style=""
              @click="handleResetSearch()"
              size="small"
              >重置</el-button
            >
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="handleSearchList()"
              size="small"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button
          size="small"
          class="btn-add"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd()"
          >新建渠道</el-button
        >
        <el-button size="small" class="btn-add" @click="ShowCategory()"
          >批量删除</el-button
        >
      </div>
      <div class="table-container">
        <el-table
          ref="resourceTable"
          :data="list"
          style="width: 100%"
          v-loading="listLoading"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="渠道分类" align="center" prop="categoryName" >

          </el-table-column>
          <el-table-column label="渠道名称" align="center">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column align="center" label="状态" prop="enableStatus">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enableStatus"
                :active-value="1"
                :inactive-value="0"
                @change="changeStatus(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="渠道人数" align="center" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.memberCount }}</template>
          </el-table-column>
          <el-table-column label="备注" align="center" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.note }}</template>
          </el-table-column>
          <el-table-column label="操作" width="240" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="copyText( scope.row)"
                >复制链接
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleShow(scope.$index, scope.row)"
                >查看二维码
              </el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.$index, scope.row)"
              >
                编辑
              </el-button>
              <el-button
               :disabled="scope.row.categoryId == 1"
                size="mini"
                type="text"
                @click="handleDelete(scope.$index, scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes,prev, pager, next,jumper"
          :current-page.sync="listQuery.pageNum"
          :page-size="listQuery.pageSize"
          :page-sizes="[10, 15, 20]"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <el-dialog
      :title="isEdit ? '编辑渠道' : '添加渠道'"
      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-form
        :model="resource"
        ref="resourceForm"
        label-width="150px"
        size="small"
        :rules="rules"
      >
        <el-form-item label="渠道分类：">
          <el-select
            v-model="resource.categoryId"
            placeholder="全部"
            clearable
            style="width: 250px"
          >
            <el-option
              v-for="item in Options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道名称：" prop="name">
          <el-input v-model="resource.name" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            v-model="resource.note"
            type="textarea"
            :rows="5"
            maxlength="200"
            show-word-limit
            style="width: 250px"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleDialogConfirm('resourceForm')"
          size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog :visible.sync="dialogShow" width="40%" :title="`渠道：${title}`">
      <img style="display: block; margin: auto" :src="imgDown" alt="" />
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogShow = false">取消下载</el-button>
        <el-button
          type="primary"
          @click="Dialogdown('resourceForm')"
          size="small"
          >下载二维码</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  haibao,
  catelist,
  haibaopage,
  uphaibao,
  deletecates,
  cateenableStatusStatus,
  haibaodownload,
  downloadhaibao,
} from "@/api/article";
import request from "@/utils/request";
import { listAllCate } from "@/api/resourceCategory";
import { formatDate } from "@/utils/date";

const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  nameKeyword: null,
  urlKeyword: null,
  categoryId: null,
};
const defaultResource = {
  id: null,
  name: null,
  url: null,
  categoryId: null,
  description: "",
};
export default {
  name: "resourceList",
  data() {
    return {
      dataId: "",
      imgDown: "",
      dialogShow: false,
      listselster: [],
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      resource: Object.assign({}, defaultResource),
      isEdit: false,
      categoryOptions: [],
      Options: [],
      defaultCategoryId: null,
      rules: {
        name: [{ required: true, message: "请输入渠道名称", trigger: "blur" }],
        url: [{ required: true, message: "请输入渠道路径", trigger: "blur" }],
      },
      title: ''
    };
  },
   created() {
    this.getCateList();
    this.getList();
  },

  filters: {
    formatDateTime(time) {
      if (time == null || time === "") {
        return "N/A";
      }
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
  },
  methods: {
    async copyText(row) {
      try {
        const currentEnv = process.env.BASE_API;
        var getip = currentEnv;
        var getindex = getip.indexOf("/api"); //获取指定字符串在原字符串条中的位置
        var getstr = getip.substring(0, getindex); //进行位置截取，从零到指定字符串所在的位置
        var obj = {
          text: "",
        };
        if (getstr == "https://dev-manage.julimeng.com") {
          obj.text = "https://dev-manage.julimeng.com/3h5/#/?channelCode=" + row.pinYin ;
        } else if (getstr == "https://test-manage.julimeng.com") {
          obj.text = "https://test-manage.julimeng.com/3h5/#/?channelCode=" + row.pinYin ;
        } else if (getstr == "https://uat-manage.shengdaiqifu.com") {
          obj.text = "https://dev-manage.julimeng.com/3h5/#/?channelCode=" + row.pinYin ;
        } else {
          obj.text = "https://manage.shengdaiqifu.com/3h5/#/?channelCode=" + row.pinYin ;
        }
        const textToCopy = obj.text;
        await navigator.clipboard.writeText(textToCopy);
        this.$message({
          type: "success",
          message: "复制成功!",
        });
      } catch (err) {
        console.error("复制失败", err);
      }
    },
    Dialogdown(fileName) {
      this.downloadFile("二维码.png", this.imgDown);
    },
    downloadFile(fileName, content) {
      let aLink = document.createElement("a");
      let blob = this.base64ToBlob(content); //new Blob([content]);

      let evt = document.createEvent("HTMLEvents");
      console.log("点击下载", evt);
      evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    },
    base64ToBlob(code) {
      let parts = code.split(";base64,");
      let contentType = parts[0].split(":")[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;

      let uInt8Array = new Uint8Array(rawLength);

      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    },

    changeStatus(v) {
      cateenableStatusStatus({
        id: v.id,
        enableStatus: v.enableStatus,
      }).then((res) => {
        this.$message.success("操作成功");
        this.getList();
      });
    },
    handleSelectionChange(e) {
      this.listselster = e;
    },
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
      this.getList();
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.resource = Object.assign({}, defaultResource);
      this.resource.categoryId = this.defaultCategoryId;
    },
    ShowCategory() {
      this.$confirm("是否删除该资源?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let arr = [];
        this.listselster.map((item) => {
          arr.push(item.id);
        });

        console.log(arr);

        deletecates(arr).then((response) => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        });
      });
    },
    handleDelete(index, row) {
      this.$confirm("是否要删除该资源?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let arr = [];
        arr.push(row.id);
        console.log(arr);

        deletecates(arr).then((response) => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        });
      });
    },
    handleUpdate(index, row) {
      this.dialogVisible = true;
      this.isEdit = true;
      this.resource = Object.assign({}, row);
    },
    handleShow(e, row) {
      this.title = row.categoryName +  '-' +  row.name
      this.dataId = row.id;
      const currentEnv = process.env.BASE_API;
      var getip = currentEnv;
      var getindex = getip.indexOf("/api"); //获取指定字符串在原字符串条中的位置
      var getstr = getip.substring(0, getindex); //进行位置截取，从零到指定字符串所在的位置
      var obj = {
        text: "",
      };
      if (getstr == "https://dev-manage.julimeng.com") {
        obj.text = "https://dev-manage.julimeng.com/3h5/#/?channelCode=" + row.pinYin ;
      } else if (getstr == "https://test-manage.julimeng.com") {
        obj.text = "https://test-manage.julimeng.com/3h5/#/?channelCode=" + row.pinYin ;
      } else if (getstr == "https://uat-manage.shengdaiqifu.com") {
        obj.text = "https://dev-manage.julimeng.com/3h5/#/?channelCode=" + row.pinYin ;
      } else {
        obj.text = "https://manage.shengdaiqifu.com/3h5/#/?channelCode=" + row.pinYin ;
      }
      haibaodownload(obj).then((res) => {
        this.dialogShow = true;
        this.imgDown = res.data;
      });
    },
    handleDialogConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm("是否要确认?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            if (this.isEdit) {
              uphaibao(this.resource).then((response) => {
                this.$message({
                  message: "修改成功！",
                  type: "success",
                });
                this.dialogVisible = false;
                this.getList();
              });
            } else {
              haibao(this.resource).then((response) => {
                this.$message({
                  message: "添加成功！",
                  type: "success",
                });
                this.dialogVisible = false;
                this.getList();
              });
            }
          });
        } else {
          return false;
        }
      });
      return;
    },
    handleShowCategory() {
      this.$router.push({ path: "/article/resourceCategory" });
    },
    getList() {
      this.listLoading = true;
      haibaopage(this.listQuery).then((response) => {
        this.listLoading = false;
        this.list = response.data.list;
        this.total = response.data.total;
      });
    },
    getCateList() {
      catelist().then((response) => {
        let cateLists = response.data;
        for (let i = 0; i < cateLists.length; i++) {
          if (cateLists[i].enableStatus == 1) {
            let cates = cateLists[i];
            this.Options.push({ label: cates.name, value: cates.id });
            this.defaultCategoryId = this.Options[0].value;
          }
          let cate = cateLists[i];
          this.categoryOptions.push({ label: cate.name, value: cate.id });
        }
      });
    },
  },
};
</script>
<style scoped>
.app-container {
  height: calc(100vh - 50px);
  background-color: #f5f5f5;
  padding: 20px;
}
</style>
